package com.yang.sso.oauth2.service.userDetils;

import cn.hutool.core.lang.Assert;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.yang.sso.oauth2.mapper.UserMapper;
import com.yang.sso.oauth2.model.MyUserDetails;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.yang.common.core.constant.SystemConstant;
import org.yang.common.core.model.UserInfo;

import java.util.*;

/**
 * 自定认证实现
 *
 * @author: lslands
 * @version: 1.0
 * @create: 2024/5/12
 * @description:
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private UserMapper userMapper;


    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
       try {
           UserInfo userInfo = Optional.ofNullable(userMapper.selectUserInfo(username))
                   .orElseThrow(() -> new UsernameNotFoundException("用户不存在"));
           Set<String> permssions = null;
           if(!userInfo.getRoles().isEmpty()){
               permssions=userInfo.getRoles().containsAll(SystemConstant.SUPER_ROLE)?
                       SystemConstant.SUPER_AUTHORIZE:
                       Optional.ofNullable(userMapper.selectAuthorizeByRoleId(userInfo.getRoles()))
                               .orElse(new HashSet<>());
           }
           return new MyUserDetails(userInfo,permssions);
       }catch (Exception e){
           e.printStackTrace();
       }
       throw new UsernameNotFoundException("用户不存在");
    }


    public Map<String, Object> getUserInfoMap(String username) throws UsernameNotFoundException {
        try {
            Map<String, Object> map=new HashMap<>();
            map.put("username", username);
            map.put("nickname", "测试");
//            UserInfo userInfo = Optional.ofNullable(userMapper.selectUserInfo(username))
//                    .orElseThrow(() -> new UsernameNotFoundException("用户不存在"));
//            Set<String> permssions = Optional.ofNullable(userMapper.selectAuthorizeByRoleId(userInfo.getRoles()))
//                    .orElse(new HashSet<>());
//            userInfo.setPerms(permssions);
//            Map<String, Object> map = JSON.parseObject(JSON.toJSONString(userInfo), new TypeReference<Map<String, Object>>(){});

            return map;
        }catch (Exception e){
            e.printStackTrace();
        }
        throw new UsernameNotFoundException("用户不存在");
    }
}
